﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using Microsoft.Xna.Framework;
using Pavilion;

namespace Pavilion.GameTools
{
    public class CameraTool : GameToolBase
    {
        private string focusName;
        private Rectangle focusBounds;

        public override void Initialize(GameItem gameItem)
        {
            gameItem.UpdateLogic += new Action<GameTime>(GameItem_UpdateLogic);
        }

        private void GameItem_UpdateLogic(GameTime gameTime)
        {
            UpdateScreen();
        }

        public override void Deserialize(XElement xmlProperties)
        {
            focusName = xmlProperties.Attribute("Focus").Value;
            focusBounds = new Rectangle(GameEngine.WindowWidth / 2 - 150, GameEngine.WindowHeight / 2 - 150, 250, 250);
        }

        public override void Serialize()
        {
            throw new NotImplementedException();
        }

        private void UpdateScreen()
        {
            PhysicalData physicalData = PhysicalTypeTool.PhysicalDataCollection[focusName];

            float xDistance = 0f;
            float yDistance = 0f;

            if (physicalData.Position.X < focusBounds.Left)
                xDistance = (int)physicalData.Position.X - focusBounds.Left;
            else if (physicalData.Position.X > focusBounds.Right)
                xDistance = (int)physicalData.Position.X - focusBounds.Right;

            if (physicalData.Position.Y < focusBounds.Top)
                yDistance = (int)physicalData.Position.Y - focusBounds.Top;
            else if (physicalData.Position.Y > focusBounds.Bottom)
                yDistance = (int)physicalData.Position.Y - focusBounds.Bottom;

            MoveScreen(xDistance, yDistance);
        }

        private void MoveScreen(float xDistance, float yDistance)
        {
            focusBounds.X += (int)xDistance;
            focusBounds.Y += (int)yDistance;

            DrawManager.Instance.FocusStartingPoint.X += xDistance;
            DrawManager.Instance.FocusStartingPoint.Y += yDistance;
        }
    }
}
